const Koa = require("koa");
const Router = require("koa-router");

const router = new Router();
const app = new Koa();

function* createCounter() {
  let i = 0;
  while (true) {
    yield ++i;
  }
}

const counter = createCounter();

const setProperty = (obj, property, key, value) => {
  if (!obj[property]) {
    obj[property] = {};
  }
  obj[property][key] = value;
};

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const m1 = async (ctx, next) => {
  console.log("m1 start");
  setProperty(ctx, "m", "m1", counter.next().value);
  await sleep(10);
  await next();
  await sleep(10);
  setProperty(ctx, "m", "m1a", counter.next().value);
  console.log("m1 end");
};

const m2 = async (ctx, next) => {
  console.log("m2 start");
  setProperty(ctx, "m", "m2", counter.next().value);
  await sleep(10);
  await next();
  await sleep(10);
  setProperty(ctx, "m", "m2a", counter.next().value);
  console.log("m2 end");
};

const m3 = async (ctx, next) => {
  console.log("m3 start");
  setProperty(ctx, "m", "m3", counter.next().value);
  await sleep(10);
  await next();
  await sleep(10);
  setProperty(ctx, "m", "m3a", counter.next().value);
  console.log("m3 end");
};

app.use(m1);
app.use(m2);
app.use(m3);

router.get("/", async (ctx) => {
  console.log(JSON.stringify(ctx.m));
  ctx.body = JSON.parse(JSON.stringify(ctx.m));
});

// app.use(async (ctx) => {
//   if (ctx.method === "GET") {
//     if (ctx.path === "/") {
//       console.log(JSON.stringify(ctx.m));
//       ctx.body = JSON.parse(JSON.stringify(ctx.m));
//     } else {
//       ctx.status = 404;
//       ctx.body = "Not Found";
//     }
//   }
// });

app.use(router.routes(), router.allowedMethods());

app.listen(3020);
